package edu.xlh.travel.service.impl;

import edu.xlh.travel.pojo.User;
import edu.xlh.travel.service.JwtExpireService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Service
@Transactional
public class JwtExpireServiceImpl implements JwtExpireService {

    @Override
    public void jwtExpireHandle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("admin");
        sessionAndCookicHandle(request , response);
        response.sendRedirect(request.getContextPath() + "/dist/adminLogin");
    }

    private void sessionAndCookicHandle(HttpServletRequest request, HttpServletResponse response) {
        Enumeration<String> attributeNames = request.getSession().getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String key = attributeNames.nextElement().toString();
            request.getSession().removeAttribute(key);
        }
        List<Cookie> cookieList = new ArrayList<>();
        Cookie cookie = new Cookie("JSESSIONID" , "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        for (Cookie cookie1 : cookieList) {
            response.addCookie(cookie1);
        }
    }
}
